﻿using System;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Collections.Generic;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cache;
using NHibernate.Tool.hbm2ddl;
using PatentApp.Models;
using System.IO;

namespace PatentApp.Data
{
    class NHibernateCfg
    {
        private static ISessionFactory _sessionFactory;
        private static ISessionFactory SessionFactory
        {
            get{
                if (_sessionFactory == null)
                    InitializeSessionFactory();
                return _sessionFactory;
            }
        }



        private static void InitializeSessionFactory()
        {
            _sessionFactory = Fluently.Configure().Database(MsSqlCeConfiguration.Standard.ConnectionString(ConfigurationManager.ConnectionStrings[1].ConnectionString).ShowSql()).
                Mappings(m => m.FluentMappings.AddFromAssemblyOf<Pracownik>()).
                ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(false, true)).ExposeConfiguration(x => x.SetProperty("connection.release_mode", "on_close")).
                BuildSessionFactory();

            //_sessionFactory = Fluently.Configure().Database(MsSqlCeConfiguration.Standard.ConnectionString(ConfigurationManager.ConnectionStrings[1].ConnectionString).ShowSql())
            //    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Pracownik>())
            //    .ExposeConfiguration(BuildSchema).ExposeConfiguration(x => x.SetProperty("connection.release_mode", "on_close"))
            //    .BuildSessionFactory();
        }

        private static void BuildSchema(NHibernate.Cfg.Configuration configuration)
        {
            NHibernate.Tool.hbm2ddl.SchemaExport schemaExport = new NHibernate.Tool.hbm2ddl.SchemaExport(configuration);
            schemaExport.Execute(false,true,false);
        }

        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }
    }
}
